﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


// pool name is resource name!!!
public class GameObjectPoolManager : MonoBehaviour {

	private Transform poolManagerObject = null;
	private Dictionary<string, GameObjectPool> dicGameObjectPools = new Dictionary<string, GameObjectPool> ();

	private static GameObjectPoolManager _instance = null;
	public static GameObjectPoolManager Instance {
		get {
			if (_instance == null) {
				GameObject poolObject = new GameObject("_GameObjectPoolManager");
				_instance = poolObject.AddComponent <GameObjectPoolManager> ();
			}

			return _instance;
		}
	}

	void Awake() {
		if (_instance == null) {
			_instance = this;	
		}

		DontDestroyOnLoad (gameObject);
	}

	void Start() {
		poolManagerObject = gameObject.transform;
	}

	public GameObjectPool CreatePool(string poolName, GameObject prefab, int initSize) {
		GameObjectPool pool = new GameObjectPool (poolName, prefab, initSize, poolManagerObject);
		dicGameObjectPools [poolName] = pool;
		return pool;
	}

	public GameObjectPool GetPool(string poolName) {
		//Debug.Log ("Get Pool " + poolName);
		if (dicGameObjectPools.ContainsKey (poolName)) {
			//Debug.Log ("contain pool");
			return dicGameObjectPools [poolName];
		}
		return null;
	}

	public GameObject GetObject(string poolName) {
		GameObjectPool pool = GetPool (poolName);
		if (pool != null) {
			return pool.GetAvailableObject ();
		}

		return null;
	}

	public GameObject GetObjectForce(string poolName) {
		//Debug.Log ("GameObjectPoolManager GetObjectForce!" + poolName);
		GameObjectPool pool = GetPool (poolName);
		if (pool == null) {
			//Debug.Log ("create prefab");
			GameObject prefab = ResourceManager.LoadResource (poolName) as GameObject;
			if (prefab != null) {
				//Debug.Log ("create pool");
				pool = CreatePool (poolName, prefab, 1);
			} else {
				Debug.LogWarning ("ResourceManager: Load Resource failed! resource name is " + poolName);
				return null;
			}
		}

		return pool.GetAvailableObject ();
	}

	public void ReturnObject(string poolName, GameObject go) {
		if (go == null)
			return;
		
		GameObjectPool pool = GetPool (poolName);
		if (pool != null) {
			pool.ReturnObjectToPool (go);
		} else {
			Debug.LogWarning ("GameObjectPoolManager, Return object to not exsit pool! pool name is " + poolName);
		}
	}

	public void ClearPools() {
		foreach (GameObjectPool pool in dicGameObjectPools.Values) {
			pool.DestroySelf ();
		}

		dicGameObjectPools.Clear ();
	}
}
